package com.example.seenesthesis.v2;

import java.io.IOException;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;




import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;

public class MainActivity extends Activity implements CvCameraViewListener2 {
	Vibrator mVibrator;
	MediaPlayer mp;
	 private Mat                    mRgba;
	    private Mat                    mIntermediateMat;
	    private Mat                    mCul;
	    CameraBridgeViewBase mOpenCvCameraView;
	    String oldColor="";
	    public void sunet()
	    {String culoare=HueToCuloare((int)mCul.get(Y,X)[0] , (int)mCul.get(Y,X)[1], (int)mCul.get(Y,X)[2]);
	    int res=getRes(culoare);
	    if(!mp.isPlaying()||!culoare.equalsIgnoreCase(oldColor))
	    {
	    mp.reset();
		try
		{
			AssetFileDescriptor afd = MainActivity.this
					.getResources().openRawResourceFd(res);

			mp.setDataSource(afd.getFileDescriptor(),
					afd.getStartOffset(), afd.getLength());
			
			mp.setVolume(1.0f, 1.0f);
			afd.close();
			mp.prepare();
		}
		catch (IllegalArgumentException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IllegalStateException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		mp.start();}

	    oldColor=culoare;
	    
	    }
	    
	    
	    public String HueToCuloare(int hue, int sat, int bright)
		{
			String cul = "";

			int dist = (int) Math.sqrt((100 - sat) * (100 - sat) + (100 - bright)
					* (100 - bright));

			if (dist < 90)
			{
				if (hue >= 347 && hue <= 360 || hue <= 2)
				{
					cul = "rosu";
				}
				else if (hue <= 346 && hue >= 258)
				{
					cul = "mov";
				}
				else if (hue <= 257 && hue >= 208)
				{
					cul = "albastru";
				}
				else if (hue <= 207 && hue >= 161)
				{
					cul = "turcoaz";
				}
				else if (hue <= 160 && hue >= 69)
				{
					cul = "verde";
				}
				else if (hue <= 68 && hue >= 40)
				{
					cul = "galben";
				}
				else if (hue <= 39 && hue >= 3)
				{
					cul = "portocaliu";
				}
			}
			else
				cul = "gray";

			return cul;
		}
	    
	    public int getRes(String culoare)
		{
			if (culoare.equalsIgnoreCase("rosu"))
				return R.raw.a;
			else if (culoare.equalsIgnoreCase("albastru"))
				return R.raw.b;
			else if (culoare.equalsIgnoreCase("portocaliu"))
				return R.raw.c;
			else if (culoare.equalsIgnoreCase("turcoaz"))
				return R.raw.d;
			else if (culoare.equalsIgnoreCase("galben"))
				return R.raw.e;
			else if (culoare.equalsIgnoreCase("verde"))
				return R.raw.f;
			else if (culoare.equalsIgnoreCase("mov"))
				return R.raw.g;
			else
				return R.raw.h;
		}
	    
	 public void vibe()
	 {if(X>0&&Y>0){
		 sunet();
	int count=0;
	int raza=30;
	for(int i=X-raza;i<=X+raza&&i<mRgba.cols()&&i>=0;i++)
		for(int j=Y-raza;j<=Y+raza&&j<mRgba.rows()&&j>=0;j++)
		{ if(mRgba.get(j, i)[0]==255)
			count++;}
	 
		 if(count>=40)
		 {		
		mVibrator.vibrate(200);}}}
	    
	    private BaseLoaderCallback  mLoaderCallback = new BaseLoaderCallback(this) {
	        @Override
	        public void onManagerConnected(int status) {
	            switch (status) {
	                case LoaderCallbackInterface.SUCCESS:
	                {System.out.println("OpenCV loaded successfully");

	                    // Load native library after(!) OpenCV initialization
	                    System.loadLibrary("mixed_sample");

	                    mOpenCvCameraView.enableView();
	                } break;
	                default:
	                {
	                    super.onManagerConnected(status);
	                } break;
	            }
	        }
	    };
	    
	int height,width;
	int rows,cols;
	int X=-1,Y=-1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mp = new MediaPlayer();
		mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		 height = displaymetrics.heightPixels;
		 width = displaymetrics.widthPixels;
		
		super.onCreate(savedInstanceState);
		 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_main);
		 mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.surface_view);
		 mOpenCvCameraView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if(event.getAction()==MotionEvent.ACTION_UP)
				{X=-1;
				Y=-1;
				}
				else{
				X=(int)((event.getX()*cols)/width);
				Y=(int)((event.getY()*rows)/height);
				vibe();}
				return true;
			}
		});
        mOpenCvCameraView.setCvCameraViewListener(this);
	}

	

	@Override
	public void onCameraViewStarted(int width, int height) {
		// TODO Auto-generated method stub
		 mRgba = new Mat(height, width, CvType.CV_8UC4);
	        mIntermediateMat = new Mat(height, width, CvType.CV_8UC4);
	        mCul = new Mat(height, width, CvType.CV_8UC4);
	        rows=mRgba.rows();
	        cols=mRgba.cols();
	}

	@Override
	public void onCameraViewStopped() {
		 mRgba.release();
	        mCul.release();
	        mIntermediateMat.release();
	}

	@Override
	public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
		//mCul=inputFrame.rgba();
		 mRgba = inputFrame.rgba();
		 Imgproc.cvtColor(mRgba, mCul, Imgproc.COLOR_RGB2HSV, 3);
         Imgproc.Canny(inputFrame.gray(), mIntermediateMat, 80, 100);
         Imgproc.cvtColor(mIntermediateMat, mRgba, Imgproc.COLOR_GRAY2RGBA, 4);
         vibe();
		
		 return mRgba;
	}
	
	
	
	 @Override
	    public void onPause()
	    {
	        super.onPause();
	        if (mOpenCvCameraView != null)
	            mOpenCvCameraView.disableView();
	    }

	    @Override
	    public void onResume()
	    {
	        super.onResume();
	        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
	    }

	    public void onDestroy() {
	        super.onDestroy();
	        if (mOpenCvCameraView != null)
	            mOpenCvCameraView.disableView();
	    }

}
